
<style lang="less" scoped>
@import "../assets/css/config.less";
*{
  padding: 0;
  margin: 0;
}
  html{
    font-size: 16px;
  }
  .flex-row-center{
    display: flex;
    justify-content: center;
  }
  .flex-column{
    display: flex;
    flex-direction: column;
  }
  .flex-row{
    display: flex;
    justify-content: start;
  }

  .user-area{
    border-radius: 4px;
    background-color: @header-bgc;
    width: 100%;
    height: 100%;
    padding: 40px 0 0 0;
    min-height: 500px;
    .username{
      line-height: 24px; 
      font-size: 14px;
      width: 80px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap; //文本不换行，这样超出一行的部分被截取，显示...
    }
  }
  .user-area .user-pic{
    position: relative;
    margin: 0px auto;
    width: 70px;
    height: 70px;
    border-radius: 50%;
    // padding: 40px 0 0 0;
    overflow: hidden;
    padding: -2px;
  }
  .index-out{
    padding: 30px 30px;
    min-width: 1210px;
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: start;
  }
  .index-left{
    width: 20%;
    height: 100%;
    max-width: 15.625rem;
    padding: 0px 20px 0 0;
  }
  .index-right{
    width: 80%;
    padding: 20px 15px;
  }
  .user-list{
    margin: 25px auto;
    width: 90%;
  }
  .user-list-bgc{
    width: 100%;
  }
  .user-list-item{
    width: 112px;
    margin: 0 auto;
    padding: 5px 0;
    text-align: left;
    font-size: 14px;
  }
  .user-list-bgc:hover{
    font-size: 14px;
    color: @color1;
    background-color: @hover-bgc;
    cursor: pointer;
  }

  .active{
    color: @color1;
  }

  .navigation-bar{
    font-size: 0.875rem;
    padding: 0.3125rem 0;
    border-bottom: 0.0625rem solid #D9D9DC;
    .title{
      margin: 0 1.6rem 0 0;
      cursor: default;
      &:hover{
        color: @color1;
      }
    }
    .active-bar{
      width: 102%;
      border-bottom: 0.125rem solid @color1;
      transform: translateY(5.8px);
    }
  }

  .message-box{
    text-align: left;
    .title{
      font-size: 0.875rem;
      font-family: "思源黑体, 黑体";
      font-weight: 600;
      // text-shadow: 0 0.5px 1px #444,0 0.75px 1px #444;
      padding: 0.9375rem 0;
    }
  }
  .message-list{
    // background-color: @header-bgc;
    width: 10rem;
    min-height: 31.25rem;
    margin: 5px 0;
    border-right: 2px solid @header-bgc;
    border-radius: 4px;
    padding: 1rem 0.2rem 0 0;
  }


  .message-box .mes-input{
    width: 16.25rem;
    line-height: 36px;
    font-size: 14px;
    outline: none;
    border: @border;
    padding: 0 10px;
    border-radius: 4px;
    &:focus{
      border-color: @color2;
    }
  }

  .button{
    line-height: 36px;
    background-color: @color1;
    color: @white;
    border-radius: 4px;
    font-size: 14px;
    width: 120px;
    margin: 10px 0px;
    letter-spacing: 2px;
    outline: none;
    border: none;
    cursor: pointer;
  }
  .button:hover{
    background-color: @color2;
  }
  .button:active{
    background-color: @color3;
  }

.msg_title {
  position: relative;
  line-height: 32px;
  height: 32px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 0.875rem;
  cursor: default;
  &.hovering{
    color: @color1;
    background-color: @header-bgc;
    font-size: 600;
    transform: translateX(-5px);
    transition: transform 0.2s;
  }
  .mybadge{
    position: absolute;
    right: 10px;
    top: 5px;
    width: 7px;
    height: 7px;
    background-color: #F56C6C;
    border-radius: 50%;
  }
}
.msg-title {
  margin-right: 10px;
  padding: 0 0 0 1rem;
}
.message-content{
  padding: 2.3rem;
  flex: 1;
  .message-view-header{
    text-align: center;
  }
  .message-view-content{
    font-size: 0.875rem;
    line-height: 1.25rem;
    padding: 0.9375rem;
  }
}

.change-avatar {
  background-color:rgba(0, 0, 0, 0.6);
  color: @white;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  // display: flex;
  justify-content: center;
  align-items: center;
  cursor: default;
  display: none;
  &:hover{
    display: flex;
  }
}
.avatar{
  background-color: @white;
}
.avatar:hover+.change-avatar{
  display: flex;
}


.message-list-leave-active {
  transition: all .5s;
}
.message-list-leave-to
/* .list-leave-active for below version 2.1.8 */ {
  opacity: 0;
  transform: translateX(60px);
}

</style>
<style lang="less">
  @import "../assets/css/config.less";
  #message .el-select .el-input.is-focus .el-input__inner{
    border-color: @color2;
  }
</style>

<template>
  <div id="message" class="index-out">
    <div class="index-left">
      <div class="user-area">
        <div class="user-pic">
          <img class="avatar" :src="`../static/pic/avatars/${user.avatar}`" style="width:100%;height:100%" alt="">
          <div class="change-avatar" @click="showChangeAvatar">更换头像</div>
        </div>
        <div class="flex-row-center" style="margin: 10px">
          <div class="flex-column" style="text-align: left;font-size:13px;width: 60px">
            <div style="line-height:24px;">用户名：</div>
            <div style="line-height:24px;">权　限：</div>
          </div>
          <div class="flex-column" style="text-align: left;font-weight: 600;margin-left: 10px;width: 40px">
            <div class="username">{{ user.username }}</div>
            <div style="line-height:24px;font-size:13px;">{{ user.userGroup === '0' ? '学生' : user.userGroup == '1' ? '超管' : user.userGroup == '2' ? '助教' : '老师' }}</div>
          </div>
        </div>
        <div class="user-list">
          <div class="user-list-bgc">
            <div class="user-list-item" @click="toPerson">个人信息</div>
          </div>
          <div class="user-list-bgc">
            <div class="user-list-item active">我的消息</div>
          </div>
          <div class="user-list-bgc">
            <div class="user-list-item" @click="toChange">修改密码</div>
          </div>
          <div class="user-list-bgc">
            <div class="user-list-item" @click="toBindEmail">绑定邮箱</div>
          </div>
        </div>
      </div>

    </div>
    <div class="index-right">
      <div class="flex-row navigation-bar">
        <!-- <span class="title" 
        v-for="(item, index) in messagePages" :key="index" 
        :class="currentMessageType === item.type ? 'active' : ''" 
        @click="chooseMessagePage(item.type)"
        >
          <Badge :count="unreadListNum" :offset="[0,-11]" v-if="item.type === 'unread'">
            {{ item.name }}
          </Badge>
          <div>{{ item.name }}</div>
          <div class="active-bar" v-if="currentMessageType === item.type"/>
        </span> -->

        <span class="title" 
        v-if="group !== '0'"
        :class="currentMessageType === 'writed' ? 'active' : ''" 
        @click="chooseMessagePage('writed')"
        >
          <div>发送消息</div>
          <div class="active-bar" v-if="currentMessageType === 'writed'"/>
        </span>
        <span class="title" 
        :class="currentMessageType === 'application' ? 'active' : ''" 
        @click="chooseMessagePage('application')"
        >
          <Badge v-if="applicationUnreadCount" :count="applicationUnreadCount" :offset="[0,-11]">
            权限申请
          </Badge>
          <div>权限申请</div>
          <div class="active-bar" v-if="currentMessageType === 'application'"/>
        </span>
        <span class="title" 
        :class="currentMessageType === 'user_feedback' ? 'active' : ''" 
        @click="chooseMessagePage('user_feedback')"
        >
          <Badge v-if="userFeedbackUnreadCount" :count="userFeedbackUnreadCount" :offset="[0,-11]">
            用户反馈
          </Badge>
          <div v-else>用户反馈</div>
          <div class="active-bar" v-if="currentMessageType === 'user_feedback'"/>
        </span>
        <span class="title" 
        :class="currentMessageType === 'answer_notification' ? 'active' : ''" 
        @click="chooseMessagePage('answer_notification')"
        >
          <Badge v-if="answerNotificationUnreadCount" :count="answerNotificationUnreadCount" :offset="[0,-11]">
            答疑提醒
          </Badge>
          <div v-else>答疑提醒</div>
          <div class="active-bar" v-if="currentMessageType === 'answer_notification'"/>
        </span>
        <span class="title" 
        :class="currentMessageType === 'system' ? 'active' : ''" 
        @click="chooseMessagePage('system')"
        >
          <Badge v-if="systemUnreadCount" :count="systemUnreadCount" :offset="[0,-11]">
            系统消息
          </Badge>
          <div v-else>系统消息</div>
          <div class="active-bar" v-if="currentMessageType === 'system'"/>
        </span>
        <span class="title" 
        :class="currentMessageType === 'trash' ? 'active' : ''" 
        @click="chooseMessagePage('trash')"
        >
          <div>回收站</div>
          <div class="active-bar" v-if="currentMessageType === 'trash'"/>
        </span>
      </div>
      
      <div class="message-box" v-if="currentMessageType === 'writed'">
        <div class="title">发送方式</div>
        <RedioGroup :options="redioOptions" @getChoose="getChoose"/>
        <div v-if="redioState === 0">
          <div class="title">收信人</div>
          <input
            type="text"
            v-model="stuNumber"
            placeholder="请输入对方的学号"
            class="mes-input"
          />
        </div>
        <div v-if="redioState === 1">
          <div class="title">收信群体</div>
          <el-select  v-model="flags" filterable multiple placeholder="请选择要发送的群体">
            <el-option-group v-for="group in options" :key="group.label" :label="group.label">
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-option-group>
          </el-select>
        </div>
        <div class="title">内容</div>
        <div ref="editor" style="text-align:left"></div>
        <button class="button" @click="send">确定</button>
      </div>
      <div v-for="messagetype in ['application', 'answer_notification', 'user_feedback', 'system', 'trash']" :key="messagetype">
        <div class="message-box flex-row" v-if="currentMessageType === messagetype">
          <h3 style="padding:30px 0" v-if="!messageList.length && (!contentLoading)">
            暂时没有消息~
          </h3>
          <div class="message-list" v-if="messageList.length&&messageList">
            <transition-group name="message-list" tag="p">
              <div 
                v-for="(item,index) in messageList" 
                :name="index" 
                :key="item._id" 
                style="margin: 1px"
                @mouseover="hoveringMessage(index)" 
                @mouseleave="hoveringMessageEnd"
                @click="handleView(index)"
                :class="showingMsgItem&&item._id === showingMsgItem._id?'active':''"
                >
                <div class="msg_title" :class="hoveringMessageIndex === index ? 'hovering' : ''" v-if="currentMessageType !== 'writed'">
                  <!-- <el-badge is-dot class="badge-sty"> -->
                    <p v-if="item.type === 'application'" class="msg-title">权限申请</p>
                    <p v-if="item.type === 'answer_notification'" class="msg-title">答疑提醒</p>
                    <p v-if="item.type === 'user_feedback'" class="msg-title">用户反馈</p>
                    <p v-if="item.type === 'system'" class="msg-title">系统消息</p>
                  <!-- </el-badge> -->
                  <!-- <Badge v-if="item.type === 'application' && item.result === 1" status="success" />
                  <Badge v-if="item.type === 'application' && item.result === 0" status="error" /> -->
                  <Button
                    style="float: right;background-color:yellow"
                    size="small"
                    :icon="item.status !== 'trash' ? 'md-trash' : 'md-redo'"
                    :title="item.status !== 'trash' ? '删除' : '还原'"
                    type="text"
                    v-show="hoveringMessageIndex === index &&
                      deleting !== item._id"
                    @click.native.stop="removeMsg(index)"
                  ></Button>
                  <div class="el-icon-loading" v-if="deleting === item._id"></div>
                  <div class="mybadge" v-if="item.status === 'unread'"></div>
                </div>
               
              </div>
            </transition-group>
          </div>
          <div class="message-content" v-if="messageList.length&&showingMsgItem!==null">
            <Spin fix v-if="contentLoading" size="large"></Spin>
            <div class="message-view-header" v-if="showingMsgItem.type === 'application'">
              <h2>权限申请</h2>
            </div>
            <div v-if="showingMsgItem.type === 'application'">
              <p v-if="showingMsgItem.type === 'application'" class="message-view-content">
                您申请成为
                <strong v-if="showingMsgItem.target === '2'">助教</strong>
                <strong v-if="showingMsgItem.target === '3'">老师</strong> 。管理员
                <strong v-if="showingMsgItem.result === 1">通过</strong>
                <strong v-if="showingMsgItem.result === 0">拒绝</strong> 了您的申请。
              </p>
            </div>
            <div class="message-view-header" v-if="showingMsgItem.type === 'answer_notification'">
              <h2>答疑提醒</h2>
            </div>
            <div v-if="showingMsgItem.type === 'answer_notification'">
              <p
                v-if="showingMsgItem.type === 'answer_notification'"
                class="message-view-content"
              >{{ showingMsgItem.content }}</p>
            </div>
            <div class="message-view-header" v-if="showingMsgItem.type === 'user_feedback'">
              <h2>用户反馈</h2>
            </div>
            <div v-if="showingMsgItem.type === 'user_feedback'">
              <p
                v-if="showingMsgItem.type === 'user_feedback'"
                class="message-view-content"
              >{{ showingMsgItem.content }}</p>
            </div>
            <div class="message-view-header" v-if="showingMsgItem.type === 'system'">
              <h2>通知</h2>
            </div>
            <div v-if="showingMsgItem.type === 'system'">
              <div 
                v-if="showingMsgItem.type === 'system'"
                class="flexed message-view-content" 
                v-html="showingMsgItem.content"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <avatars v-if="showAvatarFlag" @handleclose="closeAvatars"/>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions} from "vuex";
import avatars from "../components/avatars.vue";
import E from "wangeditor";
import {addMessage} from "../api/api";
import RedioGroup from "../components/RedioGroup"
const listDic = {
  application: "applicationList",
  answer_notification: "answerNotificationList",
  user_feedback: "userFeedbackList",
  system: "systemList",
  trash: "messageTrashList"
};
export default {
  name: "message_page",
  data() {
    return {
      options: [
        {
          label: "身份标签",
          options: [
            {
              value: "0",
              label: "学生"
            },
            {
              value: "1",
              label: "管理员"
            },
            {
              value: "2",
              label: "助教"
            },
            {
              value: "3",
              label: "老师"
            }
          ]
        },
        {
          label: "学年",
          options: [
            {
              value: "4",
              label:
                new Date().getFullYear() -
                2 +
                "--" +
                (new Date().getFullYear() - 1)
            },
            {
              value: "5",
              label:
                new Date().getFullYear() - 1 + "--" + new Date().getFullYear()
            },
            {
              value: "6",
              label:
                new Date().getFullYear() + "--" + (new Date().getFullYear() + 1)
            }
          ]
        },
        {
          label: "课程",
          options: [
            {
              value: "7",
              label: "导论课"
            },
            {
              value: "8",
              label: "本科创新创业选修课"
            },
            {
              value: "9",
              label: "研究生创新创业课"
            },
            {
              value: "10",
              label: "移动互联网创意与创业课"
            },
            {
              value: "13",
              label: "内师大科技创新实践"
            }
          ]
        },
        {
          label: "组别",
          options: [
            {
              value: "11",
              label: "做题组"
            },
            {
              value: "12",
              label: "非做题组"
            }
          ]
        }
      ],
      flags: [],
      redioOptions: [{
        text: "私发",
        img: "../../static/pic/私发邮件.png"
      }, {
        text: "群发",
        img: "../../static/pic/群发邮件.png"
      }],
      // messagePages: [{
      //   name: "发送消息",
      //   type: "writed"
      // }, {
      //   name: "权限申请",
      //   type: "application"
      // }, {
      //   name: "用户反馈",
      //   type: "user_feedback"
      // }, {
      //   name: "答疑提醒",
      //   type: "answer_notification"
      // }, {
      //   name: "系统消息",
      //   type: "system"
      // }, {
      //   name: "回收站",
      //   type: "trash"
      // }],
      currentMessagePage: 0,
      stuNumber: "",
      deleting: '',
      group: "",
      editorContent: "",
      listLoading: true,
      contentLoading: false,
      currentMessageType: "application",
      messageContent: {},
      showingMsgItem: null,
      redioState: 0,
      hoveringMessageIndex: -1,
      showAvatarFlag: false
    };
  },
  computed: {
    ...mapState({
      applicationList: state => state.Message.applicationList,
      answerNotificationList: state => state.Message.answerNotificationList,
      userFeedbackList: state => state.Message.userFeedbackList,
      systemList: state => state.Message.systemList,
      messageTrashList: state => state.Message.messageTrashList,
      messageList() {
        return this[listDic[this.currentMessageType]];
      },
      user: function() {
        return JSON.parse(this.$store.state.user)
      },
      unreadListNum() {
        return this[listDic.unread].length;
      },
      // titleClass() {
      //   return {
      //     "not-unread-list": this.currentMessageType !== "unread"
      //   };
      // }
    }),
    ...mapGetters([
      // "messageUnreadCount",
      // "messageReadedCount",
      // "messageTrashCount"
      "applicationUnreadCount",
      "answerNotificationUnreadCount",
      "userFeedbackUnreadCount",
      "systemUnreadCount",
      "messageUnreadCount",
    ])
  },
  created(){
  },
  components: {
    RedioGroup,
    avatars
  },
  mounted() {
    this.group = JSON.parse(this.$store.state.user).userGroup;
    if(this.group !== '0'){
      this.currentMessageType = "writed";
      // 展示发送消息界面编辑框
      this.$nextTick(() => {
        this.writeMsg();
      })
    } else {
      // this.messagePages = this.messagePages.slice(1)
      this.chooseMessagePage('application')
    }
    this.listLoading = true;
    //请求获取消息列表
    this.getMessageList(this.$store.state.UUID)
      .then(() => {
        this.stopLoading("listLoading");
      })
      .catch(() => this.stopLoading("listLoading"));
    
  },
  methods: {
    ...mapMutations([
      //
    ]),
    ...mapActions([
      "getMessageList",
      "hasRead",
      "removeReaded",
      "restoreTrash"
    ]),
    
    closeAvatars(){
      this.showAvatarFlag = false
    },
    showChangeAvatar() {
      this.showAvatarFlag = true
    },
    getChoose(result){
      this.redioState = result;
    },
    chooseMessagePage(type){
      this.currentMessageType = type;
      if(type === "writed") {
        this.showingMsgItem = null;
        this.$nextTick(() => {
          this.writeMsg();
        })
      } else {
        if(this.messageList.length)
        this.handleView(0)
      }
    },
    toChange() {
      this.$router.push("/change_pass");
    },
    toBindEmail(){
      this.$router.push("/bindEmail");
    },
    toPerson(){
      this.$router.push("/person");
    },
    stopLoading(name) {
      this[name] = false;
    },
    hoveringMessage(index){
      this.hoveringMessageIndex = index;
    },
    hoveringMessageEnd(){
      this.hoveringMessageIndex = -1;
    },
    handleView(index) {
      this.contentLoading = true;
      let target = this[listDic[this.currentMessageType]][index];
      this.showingMsgItem = target;
      this.stopLoading("contentLoading");
      if (target.status === "unread")
        this.hasRead({ msg_id: target._id, type: target.type }).then(res => {
          if(res.state === true){
            this[listDic[this.currentMessageType]][index].status = 'readed'
            target = this[listDic[this.currentMessageType]][index].status
          }
        }).catch(err => {
          this.$Message.error(err);
        });
    },
    writeMsg() {
      var editor = new E(this.$refs.editor);
      editor.customConfig.onchange = html => {
        this.editorContent = html;
      };
      var url = "";
      if (process.env.NODE_ENV === "development") {
        url = "http://localhost:8080/api/uploadImg";
      } else if (process.env.NODE_ENV === "production") {
        url = "https://www.ourspark.org/api/uploadImg";
      }
      editor.customConfig.uploadImgServer = url;
      editor.customConfig.zIndex = 0;
      editor.create();
      editor.txt.html("");
    },
    send() {
      if (this.stuNumber !== "" || this.flags.length !== 0) {
        if (this.editorContent !== "") {
          var stuNo = [];
          stuNo.push(this.stuNumber);
          let json = {};
          json = {
            flags: this.flags,
            stuNo: stuNo,
            type: "system",
            content: this.editorContent
          };
          addMessage(json)
            .then(response => {
              if (response.state === true) {
                this.$Message.success("发送成功");
                this.flags = [];
                this.stuNumber =  "";
                this.redioState = 0;
                var editor = new E(this.$refs.editor);
                editor.customConfig.onchange = html => {
                  this.editorContent = html;
                };
                var url = "";
                if (process.env.NODE_ENV === "development") {
                  url = "http://localhost:8080/api/uploadImg";
                } else if (process.env.NODE_ENV === "production") {
                  url = "https://www.ourspark.org/api/uploadImg";
                }
                editor.customConfig.uploadImgServer = url;
                editor.customConfig.zIndex = 0;
                editor.create();
                editor.txt.html("");
              } else {
                this.$Message.error(response.msg);
              }
            })
            .catch(error => {
              this.$Message.error(error.status);
            });
        }
      }
    },
    removeMsg(index) {
      if(this.deleting) {
        this.$Message.error("操作过于频繁！")
        return
      }
      let item = this.messageList[index]
      const that = this
      const msg_id = item._id;
      this.deleting = item._id;
      if (item.status !== "trash") 
      this.removeReaded({ msg_id, type: item.type})
      .then(res => {
        this.hoveringMessageIndex = -1;
        if(res===1) {
          this.$Message.success("删除消息成功！")
          this.showingMsgItem = null
          this.deleting = '';
        } else {
          this.$Message.error("删除消息失败！")
        }
      });
      else this.restoreTrash({ msg_id, type: item.type })
      .then(res => {
        this.hoveringMessageIndex = -1;
        if(res) {
          this.$Message.success("还原消息成功！")
          this.showingMsgItem = null
          this.deleting = '';
        } else {
          this.$Message.error("还原消息失败！")
        }
      });
    }
  },
  }
</script>
